import axios from "axios";
import router from "@/router/index.js";
import {ElMessage} from 'element-plus'
import {getToken} from "@/util/tokenUtil.js";

const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 10000,

})

instance.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    const token = getToken()
    if (token) {
        config.headers['Authorization'] = token
    }
    return config
}, error => {
    Promise.reject(error)
})

instance.interceptors.response.use(
    (res) => {
        // console.log(res.data)
        if (res.data.code === 10) {
            ElMessage.error(res.data.msg)
            router.replace("/login")
            return Promise.reject(res.data.msg)
        } else if (res.data.code !== 0) {
            ElMessage.error(res.data.msg)
            return Promise.reject(res.data.msg)
        }
        return res
    },
    (error) => {
        // console.log(error)
        if (error) {
            const status = error.status
            switch (status) {
                case 400:
                    ElMessage.error('请求拒绝')
                    break;
                case 403:
                    ElMessage.error('无权访问')
                    break;
            }
        } else {
            if (JSON.stringify(error).includes('timeout')) {
                ElMessage.error('响应超时，请刷新页面')
            } else {
                ElMessage.error('连接服务器失败')
            }

        }

        return Promise.reject(error)
    }
)

export default instance